<template>
  <div class="loginbody">
    <div class="logindata">
      <div class="logintext">
        <h2>寒衣补助申请系统</h2>
      </div>
      <div class="formdata">
        <el-form ref="form" :model="user">
          <el-form-item prop="loginName">
            <el-input
                v-model="user.username"
                clearable
                placeholder="请输入账号"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
                v-model="user.password"
                clearable
                placeholder="请输入密码"
                show-password
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="butt">
        <el-button type="primary" @click="login" :loading="loading"
        >登录</el-button
        >
        <el-button class="shou">注册</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {ElMessage} from "element-plus";
import {_login} from '@/api/user'
import {_getMenuByUser} from '@/api/menu'
import {useRouter} from "vue-router";
import {useUserInfoStore} from '@/stores/userInfo'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const user = ref({
  username: '',
  password: '',
})
const loading = ref(false)

const login = async () => {
  loading.value = true
  try {
    const res = await _login(user.value)
    // 后端返回结构: { success, code, message, data: { token } }
    // request拦截器已经处理了code !== 200的情况，这里只处理成功的情况
    if (res && res.data && res.data.token) {
      // 保存token到 Pinia store
      userInfoStore.setToken(res.data.token)
      
      // 保存用户信息（如果后端返回了用户信息）
      if (res.data.userInfo) {
        userInfoStore.setUserInfo(res.data.userInfo)
      }
      
      // 同步保存到 localStorage，确保路由守卫能立即读取到
      const userInfoData = localStorage.getItem('userInfo')
      let userData = {}
      if (userInfoData) {
        try {
          userData = JSON.parse(userInfoData)
        } catch (e) {
          console.error('解析userInfo失败:', e)
        }
      }
      userData.token = res.data.token
      localStorage.setItem('userInfo', JSON.stringify(userData))
      
      // 获取用户菜单权限
      let firstMenuPath = '/user/info' // 默认跳转到个人中心
      try {
        const menuRes = await _getMenuByUser()
        if (menuRes && menuRes.code === 200) {
          const menuList = menuRes.data.menuList || []
          userInfoStore.setMenuList(menuList)
          
          // 查找第一个可访问的菜单路径
          const findFirstMenuPath = (menus) => {
            for (const menu of menus) {
              // 如果菜单启用且有路径
              if (menu.menuStatus === 0 && menu.menuPath && menu.menuPath !== '#') {
                // 如果有子菜单，先查找子菜单
                if (menu.children && menu.children.length > 0) {
                  const childPath = findFirstMenuPath(menu.children)
                  if (childPath) return childPath
                }
                // 返回当前菜单路径
                return menu.menuPath
              }
            }
            return null
          }
          
          const foundPath = findFirstMenuPath(menuList)
          if (foundPath) {
            firstMenuPath = foundPath
          }
        }
      } catch (menuError) {
        console.error('获取菜单失败:', menuError)
        // 即使获取菜单失败，也允许登录
      }
      
      ElMessage({
        message: '登录成功',
        type: 'success',
      })
      
      // 使用 setTimeout 确保数据已保存
      setTimeout(() => {
        router.push({path: firstMenuPath})
      }, 100)
    } else {
      ElMessage({
        message: '登录失败，未获取到token',
        type: 'error',
      })
    }
  } catch (error) {
    // 错误已经在request拦截器中处理，这里不需要再次提示
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

</script>

<style scoped>
.loginbody {
  width: 100%;
  height: 100%;
  min-width: 1000px;
  background-image: url("../assets/bizi.png");
  background-size: 100% 100%;
  background-position: center center;
  overflow: auto;
  background-repeat: no-repeat;
  position: fixed;
  line-height: 100%;
  padding-top: 150px;
}

.logintext {
  margin-bottom: 20px;
  line-height: 50px;
  text-align: center;
  font-size: 30px;
  font-weight: bolder;
  color: white;
  text-shadow: 2px 2px 4px #000000;
}

.logindata {
  width: 400px;
  height: 300px;
  transform: translate(-50%);
  margin-left: 50%;
}

.butt {
  margin-top: 10px;
  text-align: center;
}

.shou {
  cursor: pointer;
  color: #606266;
}
</style>


